package util

import (
	"log"

	"github.com/tidwall/gjson"

	"github.com/ddliu/go-httpclient"
)

// 绑定为json
// type UserLoginResp struct {
// 	Code int    `form:"code" json:"code" xml:"code"  binding:"required"`
// 	Msg  string `form:"msg" json:"msg" xml:"msg" binding:"required"`
// 	Data string `form:"data" json:"data" xml:"data" binding:"required"`
// }

func PassportLogin(username string, password string) ([]byte, error) {

	res, err := httpclient.PostJson("http://passport.hupu.io/passport/login", map[string]string{
		"username": username,
		"password": password,
	})

	body, err := res.ReadAll()
	if err != nil {
		log.Fatal(err)
	}
	return body, err
}

func GetUserInfo(token string) ([]byte, error) {
	auth_resp, err := httpclient.PostJson("http://passport.hupu.io/passport/authenticate", map[string]string{
		"ticket": token,
	})

	if err != nil {
		log.Fatal(err)
	}

	auth_body, err := auth_resp.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	access_token := gjson.GetBytes(auth_body, "data.access_token")

	userinfo_resp, err := httpclient.WithHeader("Authorization", access_token.String()).Get("http://passport.hupu.io/passport/api/v1/user/info")

	if err != nil {
		log.Fatal(err)
	}
	userinfo_body, err := userinfo_resp.ReadAll()
	return userinfo_body, err
}
